// 设置 Cesium ion 访问令牌
Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJjNmU4ZTRhOC03ZTEzLTQ1NTctYjYyNS0wMzJkZjcxNDBlNmIiLCJpZCI6NTY0MiwiaWF0IjoxNjc1OTM0NTc5fQ.wS02OipgTbtOxTEHwTzFOvSIqSUPr1RCNC4qXkWXhgc';

// 创建 Viewer 实例
const viewer = new Cesium.Viewer('cesiumContainer', {
    // terrainProvider: Cesium.createWorldTerrainAsync(),
    baseLayerPicker: true,
    geocoder: true,
    homeButton: true,
    sceneModePicker: true,
    navigationHelpButton: true,
    animation: true,
    timeline: true,
    fullscreenButton: true
});

// 启用地形深度测试
viewer.scene.globe.enableLighting = true;
viewer.scene.globe.depthTestAgainstTerrain = true;

// 定义正方形的顶点坐标
const positions = Cesium.Cartesian3.fromDegreesArray([-75.0, 40.0, -75.0, 40.1, -74.9, 40.1, -74.9, 40.0]);

// 创建几何体实例
const geometry = new Cesium.GeometryInstance({
    geometry: new Cesium.PolygonGeometry({
        polygonHierarchy: new Cesium.PolygonHierarchy(positions),
        vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT
    })
});

// 创建自定义着色器材质
// const material = new Cesium.Material({
//     fabric: {
//         type: 'CustomShader',
//         uniforms: {
//             image: new Cesium.TextureUniform({
//                 url: '1.jpg'
//             }),
//             time: 0
//         },
//         source: `
//             uniform sampler2D image;
//             uniform float time;

//             czm_material czm_getMaterial(czm_materialInput materialInput) {
//                 czm_material material = czm_getDefaultMaterial(materialInput);

//                 vec2 st = materialInput.st;

//                 // 添加一些简单的动画效果
//                 st.s += sin(st.t * 10.0 + time) * 0.01;

//                 vec4 textureColor = texture2D(image, st);

//                 material.diffuse = textureColor.rgb;
//                 material.alpha = textureColor.a;

//                 return material;
//             }
//         `
//     }
// });

const SHADER_SOURCE = `
uniform sampler2D image;
uniform sampler2D nextImage;
uniform float time;
uniform float blend;

czm_material czm_getMaterial(czm_materialInput materialInput) {
    czm_material material = czm_getDefaultMaterial(materialInput);

      
    // 创建动画效果的UV坐标
    vec2 st = materialInput.st;
    
    // 方式1：平移动画
    // st.s += time * 0.1; // 水平移动
    // st.t += sin(time) * 0.1; // 垂直波动
    
    // 或者方式2：旋转动画
    // float angle = time;
    // vec2 center = vec2(0.5, 0.5);
    // vec2 translated = st - center;
    // vec2 rotated = vec2(
    //     translated.x * cos(angle) - translated.y * sin(angle),
    //     translated.x * sin(angle) + translated.y * cos(angle)
    // );
    // st = rotated + center; 


// 缩放动画
// st = (st - 0.5) * (1.0 + sin(time) * 0.2) + 0.5;

// 扭曲动画
st.s += sin(st.t * 10.0 + time) * 0.1;

// 波纹动画
// float dist = distance(st, vec2(0.5));
// st += sin(dist * 10.0 - time) * 0.03;  
// 确保UV坐标在0-1范围内循环
    st = fract(st);
    
 // 获取当前图片和下一张图片的颜色
        vec4 currentColor = texture(image, st);
        vec4 nextColor = texture(nextImage, st);
        // 混合两张图片
        vec4 color = mix(currentColor, nextColor, blend);
    material.diffuse = color.rgb;
    material.alpha = color.a;
    return material;
}
`

function createMaterial(imageUrl) {
    return new Cesium.Material({
        fabric: {
            type: 'DynamicImage',
            uniforms: {
                image: imageUrl,
                nextImage: imageUrl, // 如果没有下一张图片，使用当前图片
                time: 0,
                blend: 0
            },
            source: SHADER_SOURCE
        }
    });
}

let material = createMaterial('./1.jpg');

// 创建外观
// const appearance = new Cesium.EllipsoidSurfaceAppearance({
//     material: material,
//     fragmentShaderSource: `
//         varying vec3 v_positionMC;
//         varying vec3 v_positionEC;
//         varying vec2 v_st;

//         void main() {
//             czm_materialInput materialInput;
//             materialInput.s = v_st.s;
//             materialInput.st = v_st;
//             materialInput.str = vec3(v_st, 0.0);
//             materialInput.normalEC = normalize(czm_normal3D * czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0)));
//             materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, materialInput.normalEC);
//             materialInput.positionToEyeEC = -v_positionEC;

//             czm_material material = czm_getMaterial(materialInput);

//             gl_FragColor = vec4(material.diffuse + material.emission, material.alpha);
//         }
//     `
// });
const appearance = new Cesium.EllipsoidSurfaceAppearance({
    material: material,
    aboveGround: true
});

// 创建 Primitive

const groundPrimitive = new Cesium.GroundPrimitive({
    geometryInstances: geometry,
    appearance: appearance,
    classificationType: Cesium.ClassificationType.TERRAIN
});

// 将 Primitive 添加到场景中
// viewer.scene.primitives.add(primitive);
viewer.scene.groundPrimitives.add(groundPrimitive);


let isTransitioning = false;
let transitionStart = 0;
const TRANSITION_DURATION = 1000; // 过渡动画持续时间（毫秒）

// 更新时间 uniform 以创建动画效果
viewer.scene.preUpdate.addEventListener(function(scene, time) {

    // material.uniforms.time =
    //     Cesium.JulianDate.secondsDifference(time, Cesium.JulianDate.fromDate(new Date(2020, 0, 1))) * 0.05;
    const currentTime = performance.now();

    // 更新动画时间
    material.uniforms.time =
        Cesium.JulianDate.secondsDifference(time, Cesium.JulianDate.fromDate(new Date(2020, 0, 1))) * 0.1;

    // 更新过渡混合值
    if (isTransitioning) {
        const progress = (currentTime - transitionStart) / TRANSITION_DURATION;
        if (progress >= 1.0) {
            isTransitioning = false;
            // material.uniforms.blend = 1.0;
            material.uniforms.image = material.uniforms.nextImage;
            material.uniforms.blend = 0.0;
        } else {
            material.uniforms.blend = progress;
        }
    }
});

// 将视图定位到正方形
viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(-75.0, 40.05, 100000)
});




// 函数：更新材质的图片
async function updateImage(newImageUrl) {


    if (isTransitioning || material.uniforms.image === newImageUrl) return; // 如果正在过渡中，忽略新的更新请求

    try {
        // 预加载新图片
        // await preloadImage(newImageUrl);

        // 开始过渡
        material.uniforms.nextImage = newImageUrl;
        isTransitioning = true;
        transitionStart = performance.now();

    } catch (error) {
        console.error('Failed to load image:', error);
    }


}


// 添加一些测试按钮来切换图片
const buttonContainer = document.createElement('div');
buttonContainer.style.position = 'absolute';
buttonContainer.style.top = '10px';
buttonContainer.style.left = '10px';
buttonContainer.style.zIndex = '1000';

const button1 = document.createElement('button');
button1.textContent = '图片1';
button1.onclick = () => updateImage('./2.jpg');

const button2 = document.createElement('button');
button2.textContent = '图片2';
button2.onclick = () => updateImage('./3.jpg');

buttonContainer.appendChild(button1);
buttonContainer.appendChild(button2);
document.body.appendChild(buttonContainer);